/*jslint vars: true, forin: true, sloppy: true */
/*global probe, angular */
probe.controller("ProjectDetail", function ($scope, $element, ocAPI, $timeout,
											 ocDialog, $filter, $interval) {
	var DI = ocDialog.queryDI($element),
		projectId = DI.share.projectId,
		p = DI.share.position || {},
		refreshProjectList = DI.share.refreshProjectList,
		deleteProject = DI.share.deleteProject,
		date = $filter('date'),
		dateFormat = 'yyyy-MM-dd',
		probePathReg = /^https?:\/\/[0-9a-zA-Z_\.\/%]+$/,
		probeOriginReg = /^[0-9a-zA-Z\/_%\.?=&#;]+$/;

	function filterUpdatetime(list) {
		var newList = [];
		angular.forEach(list, function (obj, index) {
			obj = angular.copy(obj);
			obj.updatetime = date(obj.updatetime, dateFormat);
			this.push(obj);
		}, newList);

		return newList;
	}
    $scope.configProbe = {
        name: 'probe/config',
		share: function () {
			return {
				project: $scope.project,
				path_r: probePathReg,
				origin_r: probeOriginReg
			};
		}
    };
	$scope.project = {};
	$scope.changed = function () {
		$scope.isChanged = true;
	};
	$scope.updatetime = function () {
		return date($scope.project.updatetime, dateFormat);
	};
	$scope.createtime = function () {
		return date($scope.project.createtime, dateFormat);
	};

	$scope.isChanged = false;
	$scope.tabs = {};
	function disableTab(index, condition) {
		//$scope.tabs.$tabs[index].isDisabled
		//	= condition ? false : true;
	}
	function privilegeExceptionHandle() {

	}

	function getProject(callback) {
		ocAPI.use('getProject').by(projectId, p.teamId, p.positionId)
			.then(function (data) {
				$scope.project = data.project;
				DI.$$scope.title = data.project.name + ' - 项目';
				(callback || angular.noop)();
			});
	}
	$scope.cases = [];
	function listCaseOfProject() {
		ocAPI.use('listCaseOfProject').by(projectId)
			.then(function (data) {
				$scope.cases = filterUpdatetime(data.cases);
				disableTab(2, $scope.cases.length);
			});
	}
	$scope.dictionaries = [];
	function listDictionaryOfProject() {
		ocAPI.use('listDictionaryOfProject').by(projectId)
			.then(function (data) {
				$scope.dictionaries = filterUpdatetime(data.dictionaries);
				disableTab(1, $scope.dictionaries.length);
			});
	}
	$scope.results = [];
	function listResultOfProject() {
		ocAPI.use('listResultOfProject').by(projectId)
			.then(function (data) {
				$scope.results = filterUpdatetime(data.results);
				disableTab(4, $scope.results.length);
			});
	}
	$scope.objects = [];
	function getObject() {
		ocAPI.use('getObject').by(projectId).then(function (data) {
			// It may be a null.
			$scope.objects = data.objects || [];
			disableTab(3, $scope.objects.length);
		});
	}
	$scope.token = {
		code: ''
	};
	function getToken() {
		ocAPI.use('getTokenLike').by(projectId, p.positionId).then(function (data) {
			$scope.token.code = data.token ? data.token.token : '';
		});
	}

	$scope.dictionaryList = {
		header: [
			{
				key: 'name',
				text: '字典名称',
				width: 400
			},
			{
				key: 'updatetime',
				text: '更新时间',
				width: 100
			}
		],
		visitFn: function () {
			ocDialog.getNewDI('dictionary/dictionary').then(function (DI) {
				DI.openDialogFrom();
			});
		},
		selected: -1
	};
	$scope.caseList = {
		header: [
			{
				key: 'name',
				text: '用例名称',
				width: 400
			},
			{
				key: 'updatetime',
				text: '更新时间',
				width: 100
			}
		],
        visitFn: function () {
            ocDialog.getNewDI('case/case').then(function (DI) {
                DI.openDialogFrom();
            });
        },
		selected: -1
	};
	$scope.objectList = {
		header: [
			{
				key: 'name',
				text: '子过程名称',
				width: 400
			},
			{
				key: 'updatetime',
				text: '更新时间',
				width: 100
			}
		],
        visitFn: function () {
            ocDialog.getNewDI('process/process').then(function (DI) {
                DI.openDialogFrom();
            });
        },
		selected: -1
	};
	$scope.processList = {
		header: [
			{
				key: 'name',
				text: '子过程名称',
				width: 400
			},
			{
				key: 'updatetime',
				text: '更新时间',
				width: 100
			}
		],
        visitFn: function () {
            ocDialog.getNewDI('process/process').then(function (DI) {
                DI.openDialogFrom();
            });
        }
	};
	$scope.resultList = {
		header: [
			{
				key: 'name',
				text: '报告名称',
				width: 400
			},
			{
				key: 'updatetime',
				text: '更新时间',
				width: 100
			}
		],
		visitFn: function (index) {
			var id = this[index].resultId;
			ocDialog.getNewDI('result/log', id).then(function (DI) {
				DI.openDialogFrom();
			});
		},
		selected: -1
	};
	$scope.refreshProject = function () {
		ocAPI.cache.remove("PROJECT_" + projectId);
		getProject();
	};
	$scope.updateProject = function () {
		var p = $scope.project;
		ocAPI.use('updateProject').by(projectId, {
			name: p.name,
			comment: p.comment
		}).then(function () {
			getProject();
			refreshProjectList();
		});
	};
	$scope.deleteProject = function () {
		var alert = {
			title: '删除项目',
			message: '删除项目会导致项目内所有资源一并删除\n且无法恢复，您确定吗？',
			callFn: function () {
				deleteProject(projectId);
				DI.closeDialog();
			}
		};
		ocDialog.alert(alert, DI);
	};
	$scope.deleteToken = function () {
		ocAPI.use('deleteToken').by($scope.token.code, projectId)
			.then(function () {
				$scope.token.code = '';
			});
	};

	//create token
	$scope.initDate = Date.now();
	$scope.upTime = 0;

	$scope.createToken = function () {
		if (!$scope.upTime) {
			return;
		}

		ocAPI.use('createToken').by(projectId, {
			expiredtime: $scope.initDate + $scope.upTime
		}).then(function () {
			getToken();
		});
	};
	$scope.upTimeList = [
		{
			label: '3小时',
			select: 3600*3*1000
		}, {
			label: '12小时',
			select: 3600*12*1000
		}, {
			label: '1天',
			select: 3600*24*1000
		}, {
			label: '3天',
			select: 3600*24*1000*3
		}, {
			label: '1周',
			select: 3600*24*1000*7
		}, {
			label: '2周',
			select: 3600*24*1000*7*2
		}
	];

	$scope.probeState = '连接失败';
	$scope.isProbeConnected = false;
	$scope.proebeStateStyle = {
		color: 'red'
	};
	$scope.isProbeConfigValid = function () {
		return probePathReg.test($scope.project.probePath) &&
			probeOriginReg.test($scope.project.probeOrigin);
	};
	$scope.isProbeReady = function () {
		return $scope.isProbeConfigValid() &&
			$scope.token.code !== '' &&
			$scope.isProbeConnected;
	};
	$scope.testConnection = function () {
		var Iid, Tid, iframe = angular.element('<iframe style="display:none" src="' +
				$scope.project.probePath + '/' +
				$scope.project.probeId +
				'.html"></iframe>');

		angular.element(document.body).append(iframe);

		Iid = $interval(function () {
			if (window.location.hash.match('OK')) {
				$interval.cancel(Iid);
				$timeout.cancel(Tid);
				$scope.probeState = '连接就绪';
				$scope.proebeStateStyle.color = 'green';
				$scope.isProbeConnected = true;
				window.location.hash = '';
				iframe.remove();
			}
		}, 500, 10);

		Tid = $timeout(function () {
			iframe.remove();
			$scope.probeState = '连接失败';
			$scope.proebeStateStyle.color = 'red';
			$scope.isProbeConnected = false;
		}, 5000);
	};

	$scope.refreshResultList = function () {
		ocAPI.cache.remove('RESULT_LIST_OF_PROJECT_' + projectId);
		listResultOfProject();
	};
	$scope.refreshCaseList = function () {
		ocAPI.cache.remove('CASE_LIST_OF_PROJECT_' + projectId);
		listCaseOfProject();
	};
	$scope.refreshDictionaryList = function () {
		ocAPI.cache.remove('DICTIONARY_LIST_OF_PROJECT_' + projectId);
		listDictionaryOfProject();
	};
	$scope.refreshObject = function () {
		ocAPI.cache.remove('OBJECT_OF_PROJECT_' + projectId);
		getObject();
	};

	$scope.deleteCase = function () {
		var caseId = $scope.cases[$scope.caseList.selected].caseId;
		ocAPI.use('deleteCase').by(caseId, projectId).then(function () {
			$scope.refreshCaseList();
		});
	};
	$scope.deleteDictionary = function () {
		var dictionaryId
			= $scope.dictionaries[$scope.dictionaryList.selected].dictionaryId;
		ocAPI.use('deleteDictionary').by(dictionaryId, projectId).then(function () {
			$scope.refreshDictionaryList();
		});
	};
	$scope.deleteResult = function () {
		var resultId = $scope.results[$scope.resultList.selected].resultId;
		ocAPI.use('deleteResult').by(resultId, projectId).then(function () {
			$scope.refreshResultList();
		});
	};

	//init
	getToken();
	getProject(function () {
		$scope.testConnection();
	});
	listCaseOfProject();
	listDictionaryOfProject();
	listResultOfProject();
	getObject();

	//style control
	$scope.probeEnter = function (e) {
		angular.element(e.target).removeClass('rotate-leave').addClass('rotate-enter');
	};
	$scope.probeLeave = function (e) {
		angular.element(e.target).removeClass('rotate-enter').addClass('rotate-leave');
	};
});
